import React, { Children, Fragment } from 'react';
import { Modal, Spin, Row, Col, Card, Button } from 'antd';
import styles from './style.less';
import { AxButton, AxButtonCancel, AxCard, AxQuestion } from '@/components/AxBase';
import AxPageHeaderWrapper from '@/components/AxBase/AxPageHeaderWrapper';
import IconFont from '@/assets/iconfont';

/** 自定义Modal
 * @param confirmLoading 提交状态
 */
export default class AxModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmLoading: false,
      loading: false,
    };
    this.forModalRef = element => {
      if (element && element.parentNode && element.parentNode.previousSibling) {
        const t = element.parentNode.previousSibling;
        t.addEventListener('mousedown', this.onMouseDown);
        t.addEventListener('mouseup', this.onMouseUp);
      }
      if (element && element.parentNode && element.parentNode.parentNode) {
        this.axModalRef = element.parentNode.parentNode;
        // this.axModalRef.addEventListener("mousedown", this.onMouseDown);
        // this.axModalRef.addEventListener("mouseup", this.onMouseUp);
      }
    };
  }

  componentDidMount() {
    this.handleRead();
  }

  componentWillReceiveProps(newProps) {
    const { confirmLoading: confirmLoadingFromProps } = newProps;
    const { confirmLoading } = this.state;

    if (confirmLoadingFromProps !== undefined && confirmLoadingFromProps !== confirmLoading) {
      this.setState({
        confirmLoading: confirmLoadingFromProps,
      });
    }
  }

  /** 读取 */
  handleRead = () => {
    const { handleRead, showLoading = true } = this.props;
    if (handleRead) {
      if (showLoading === true) {
        this.setState({
          loading: true,
        });
      }
      handleRead()
        .catch(() => {
          this.setState(() => ({
            loading: false,
          }));
        })
        .finally(() => {
          this.setState(() => ({
            loading: false,
          }));
        });
    }
  };

  /** 保存 */
  handleCreate = () => {
    const { form, handleCreate, isCardPage } = this.props;
    if (handleCreate) {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        this.setState({
          confirmLoading: true,
        });

        /** 处理提交的时间格式 */
        for (let p in fieldsValue) {
          if (p.toLowerCase().indexOf('time') > -1 || p.toLowerCase().indexOf('date') > -1) {
            const v = fieldsValue[p];
            if (v && v.length === 2 && v[0].format && v[1].format) {
              fieldsValue[p] = v[0].format(v._f) + '~' + v[1].format(v._f);
              fieldsValue[p + 'Start'] = v[0].format(v._f);
              fieldsValue[p + 'End'] = v[1].format(v._f);
            } else if (v && v.format && v._f) {
              fieldsValue[p] = v.format(v._f);
            }
          }
          if (fieldsValue[p] && fieldsValue[p].toHTML) {
            fieldsValue[p] = fieldsValue[p].toHTML();
          }
          /** 去掉前后空格 */
          if (typeof fieldsValue[p] === 'string') {
            fieldsValue[p] = fieldsValue[p].trim();
          }
        }
        if (isCardPage === true)
          handleCreate(fieldsValue).finally(() => {
            this.setState(() => ({
              confirmLoading: false,
            }));
          });
        else
          handleCreate(fieldsValue).catch(() => {
            this.setState(() => ({
              confirmLoading: false,
            }));
          });
      });
    }
  };

  /** 获取鼠标点击title时的坐标、title的坐标以及两者的位移 */
  getPosition = e => {
    // Modal弹框的坐标
    const X = this.axModalRef.getBoundingClientRect().left;
    const Y = this.axModalRef.getBoundingClientRect().top;
    // 鼠标点击的坐标
    let mouseX = 0,
      mouseY = 0;
    if (e.pageX || e.pageY) {
      //ff,chrome等浏览器
      mouseX = e.pageX;
      mouseY = e.pageY;
    } else {
      mouseX = e.clientX + document.body.scrollLeft - document.body.clientLeft;
      mouseY = e.clientY + document.body.scrollTop - document.body.clientTop;
    }
    // 鼠标点击位置与modal的位移
    const diffX = mouseX - X;
    const diffY = mouseY - Y;
    return { X, Y, mouseX, mouseY, diffX, diffY };
  };

  /**
   * 鼠标按下，设置modal状态为可移动，并注册鼠标移动事件
   * 计算鼠标按下时，指针所在位置与modal位置以及两者的差值
   **/
  onMouseDown = e => {
    const position = this.getPosition(e);
    window.onmousemove = this.onMouseMove;
    this.setState({ moving: true, diffX: position.diffX, diffY: position.diffY });
  };

  // 松开鼠标，设置modal状态为不可移动,
  onMouseUp = e => {
    this.setState({ moving: false });
  };

  // 鼠标移动重新设置modal的位置
  onMouseMove = e => {
    const { moving, diffX, diffY } = this.state;
    if (moving) {
      // 获取鼠标位置数据
      const position = this.getPosition(e);
      // 计算modal应该随鼠标移动到的坐标
      const x = position.mouseX - diffX;
      const y = position.mouseY - diffY;
      // 窗口大小
      const { clientWidth, clientHeight } = document.documentElement;
      // const modal = document.getElementsByClassName("ant-modal-content");
      if (this.axModalRef) {
        // const m = modal[0];
        const m = this.axModalRef;
        // 计算modal坐标的最大值
        const maxHeight = clientHeight - m.offsetHeight;
        const maxWidth = clientWidth - m.offsetWidth;
        // 判断得出modal的最终位置，不得超出浏览器可见窗口
        const left = x > 0 ? (x < maxWidth ? x : maxWidth) : 0;
        const top = y > 0 ? (y < maxHeight ? y : maxHeight) : 0;
        // this.setState({ pageX: left, pageY: top });
        this.setState({ pageX: x, pageY: y });
      }
    }
  };

  render() {
    const { items = [], handleVisible, hiddenItems = [],
      children, isCardPage = false,
      onBack = true, froalaCard = false,
      cardPageOperateBtn = true,/** 是否有操作按钮 */
      title,
      froalaCardTitle, footer, ...rest } = this.props;
    const { confirmLoading, loading, pageX, pageY } = this.state;
    const len = items.length;

    /** title组件 */
    let titleComponent;
    if (title && title.label && title.menuId) {
      titleComponent = <AxQuestion label={title.label} menuId={title.menuId} />;
    }
    else {
      titleComponent = title;
    }

    let cardPage = (
      // <AxPageHeaderWrapper onBack={onBack} title={titleComponent}>
      <Card>
        {items.map((i, idx) => (
          <div key={idx}>{i}</div>
        ))}
        <div style={{ display: 'none' }}>
          {hiddenItems.map((i, idx) => (
            <div key={len + idx}>{i}</div>
          ))}
        </div>
        {children}
        {cardPageOperateBtn && <AxCard flex={24} height={55} bodyStyle={{ padding: 10, marginTop: 3, float: 'right' }}>
          <div className='ant-modal-footer' style={{ borderTop: '0' }}>
            {footer ? footer :
              <>
                <AxButtonCancel axback={true} >
                  取消
                  </AxButtonCancel>
                <AxButton type="primary" onClick={() => this.handleCreate()} loading={confirmLoading} >
                  <IconFont type='iconsave' />
                    保存
                  </AxButton>
              </>
            }
          </div>
        </AxCard>}
      </Card>
      // </AxPageHeaderWrapper>
    );

    if (froalaCard === true) {
      cardPage = (
        <>
          {froalaCardTitle && <AxCard
            flex={24}
            height={32}
            bodyStyle={{ paddingTop: 4, paddingBottom: 4, marginBottom: 2 }}
          >
            <span style={{ fontSize: 16, color: "blue", fontWeight: "bold" }}>{froalaCardTitle}</span>
          </AxCard>}
          {items.map((i, idx) => (
            <div key={idx}>{i}</div>
          ))}
          <div style={{ display: 'none' }}>
            {hiddenItems.map((i, idx) => (
              <div key={len + idx}>{i}</div>
            ))}
          </div>
          {children}
          {this.props.handleCreate && <AxCard flex={24} height={55} bodyStyle={{ padding: 10, marginTop: 3, float: 'right' }}>
            <AxButton onClick={() => this.handleCreate()} loading={confirmLoading} >
              <IconFont type='iconsave' />
              保存
            </AxButton>
          </AxCard>}
        </>
      );
    }
debugger
    return isCardPage ? cardPage : (
      <Modal
        destroyOnClose
        onOk={this.handleCreate}
        confirmLoading={confirmLoading}
        onCancel={() => handleVisible()}
        cancelText={<><IconFont type='iconquxiao' /><span style={{ marginLeft: 8 }}>取消</span></>}
        okText={<><IconFont type='iconsave' /><span style={{ marginLeft: 8 }}>保存</span></>}
        cancelButtonProps={{
          className: 'ax-btn-cancel'
        }}
        style={{
          marginLeft: pageX,
          top: pageY,
        }}
        maskClosable={false}
        width="45%"
        footer={footer}
        title={titleComponent}
        {...rest}
      >
        <div ref={this.forModalRef}></div>
        {loading && (
          <div className={styles.axLoadingContainer}>
            <Spin />
          </div>
        )}
        {items.map((i, idx) => (
          <div key={idx}>{i}</div>
        ))}
        <div style={{ display: 'none' }}>
          {hiddenItems.map((i, idx) => (
            <div key={len + idx}>{i}</div>
          ))}
        </div>
        {children}
      </Modal>
    );
  }
}

/** 两列布局Modal（24删格布局） */
export function AxGridTwoModal(props) {
  const { items, ...rest } = props;
  function GetCol() {
    const rows = [];
    let cols = [];
    let nextRow = false;
    const len = items.length - 1;
    items.forEach((i, idx) => {
      if (i === false) {
        return;
      }
      /** 占整行 */
      if (i.props.wholerow === 'two') {
        cols.push(<Col span={24}>{i}</Col>);
        nextRow = true;
      } else {
        cols.push(<Col span={12}>{i}</Col>);
        if (cols.length === 2) {
          nextRow = true;
        }
      }
      if (nextRow === true || len === idx) {
        rows.push(
          <Row>
            {cols.map((i, idx) => (
              <Fragment key={idx}>{i}</Fragment>
            ))}
          </Row>,
        );
        cols = [];
        nextRow = false;
      }
    });
    return rows;
  }
  return <AxModal width="45%" items={GetCol()} {...rest}></AxModal>;
}

/** 三列布局Modal（24删格布局） */
export function AxGridThreeModal(props) {
  const { items, ...rest } = props;
  function GetCol() {
    const rows = [];
    let cols = [];
    let colsLen = 0;
    let nextRow = false;
    const len = items.length - 1;
    items.forEach((i, idx) => {
      if (i === false) {
        return;
      }
      /** 占整行 */
      if (i.props.wholerow === 'three') {
        cols.push(<Col span={24}>{i}</Col>);
        nextRow = true;
      }
      else if (i.props.wholerow === 'two') {
        cols.push(<Col span={16}>{i}</Col>);
        colsLen += 2;
        if (colsLen === 3) {
          nextRow = true;
        }
      } else {
        cols.push(<Col span={8}>{i}</Col>);
        colsLen++;
        if (colsLen === 3) {
          nextRow = true;
        }
      }
      if (nextRow === true || len === idx) {
        rows.push(
          <Row>
            {cols.map((i, idx) => (
              <Fragment key={idx}>{i}</Fragment>
            ))}
          </Row>,
        );
        cols = [];
        colsLen = 0;
        nextRow = false;
      }
    });
    return rows;
  }
  return <AxModal width="60%" items={GetCol()} {...rest}></AxModal>;
}
